//获取关键字
var keyword = decodeURIComponent(getQueryString('keyword'));                                             //参数1
if(keyword == "null"){
	keyword = "";
}
window.sessionStorage.type = getQueryString('categoryCode');                                             //参数2
if(window.sessionStorage.type){
	var type = window.sessionStorage.type;           
}else{
	var type = "null";
}
console.log(window.sessionStorage.type);                                                              

var page = 1;                                                                                            //参数6
var num = 1;
//JQ代码模块
$(function(){
	$("#toSearch").click(function(){
		var _keyword = $(this).parent().prev().find("input").val();
		if(_keyword != ""){
			//sessionStorage.getItem("keyword",_keyword);
			_keyword = encodeURI(_keyword); 
			_keyword = encodeURI(_keyword); 
			location.href = "searchResult.html?keyword=" + _keyword;
		}
	})
	if(keyword != "null"){
		$("#toSearch").parent().prev().find("input").val(keyword);
	}
})


//angular模块
var app = angular.module("myApp",["globalApp"]);

app.controller("myCtrl",function($scope, $http,$timeout,getShopping){
	$scope.keyword = decodeURIComponent(getQueryString('keyword'));
	
	//用来判断搜索商品是否为空
	$scope.hide = false;
	$scope.show = true;
	//三个选择的名称
	$scope.arr1 = {"ranking":"综合排序","area":"地区不限","price":"价格范围"};
	//价格范围
	$scope.arr2 = {"minPrice":"","maxPrice":""};                                                           //参数3、4
	$scope.rank = "";                                                                                      //参数5
	//seclection_content部分三个过滤项的点击事件
	$scope.ranking = false;
	$scope.area = false;
	$scope.price = false;
	
	$scope.seclect = function($event){
		switch($($event.target).text()){
			case $scope.arr1.ranking : 
			    $scope.ranking = true;
				$scope.area = false;
			    $scope.price = false;
			    break;
			case $scope.arr1.area :  
			    $scope.ranking = false;
				$scope.area = true;
			    $scope.price = false;
			    $http({
			        method : "post",
			        dataType: "json",
					withCredentials: true,	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
				    crossDomain: true,
				    'Content-Type': 'application/x-www-form-urlencoded',
				    data:{
				    	parentId : 1
				    },
			        async:true,
			        url : host + "/terminal/chinaRegion/list"
			   }).success(function(response){
			        if(response.code == 2000){
			        	$scope.city = response.data.regionArrayList;
			        }
			    }).error(function(response){
			    	console.log(response);
			    });
			    break;
			case $scope.arr1.price:
			    $scope.ranking = false;
				$scope.area = false;
			    $scope.price = true;
			    break;
		}
		//防止事件冒泡
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}
	
	$scope.rankingTitle = function($event){
		$scope.arr1.ranking = $($event.target).text();
		$($event.target).addClass("ranking_checked").siblings().removeClass("ranking_checked");
		switch($($event.target).text()){
			case "综合排序" :
			    $scope.rank = "undefined";
			    console.log($scope.rank);
			    break;
			case "人气排序" :
			    $scope.rank = "sales";
			    break;
			case "价格最低" :
				$scope.rank = "minPrice";
			    break;
			case "价格最高" :
				$scope.rank = "maxPrice";
			    break;    
		}
		$scope.hide = false;
		num = 1;
		getShopping.initShopping(keyword,type,$scope.arr2.minPrice,$scope.arr2.maxPrice,$scope.rank,1,function(response){
			$scope.arr = response.data.goods;
			console.log(response);
		})
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}
	
	$scope.areaTitle = function($event){
		$($event.target).addClass("area_checked").siblings().removeClass("area_checked");
		$scope.arr1.area = $($event.target).text();
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}
	
	/*$scope.priceTitle = function($event){
		//$($event.target).addClass("price_checked").siblings().removeClass("price_checked");
		//防止事件冒泡
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}*/
	
	$scope.sure = function($event){
		$scope.arr2.minPrice = $("#minPrice").val();
		$scope.arr2.maxPrice = $("#maxPrice").val();
		$scope.ranking = false;
		$scope.area = false;
		$scope.price = false;
		$scope.hide = false;
		getShopping.initShopping(keyword,type,$scope.arr2.minPrice,$scope.arr2.maxPrice,$scope.rank,1,function(response){
			$scope.arr = response.data.goods;
		})
		
		//防止事件冒泡
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}
	
	$scope.cancelBubble = function($event){
		//防止事件冒泡
		$event.stopPropagation();  
		$event.cancelBubble = true;
	}
	//点击，将三个选择隐藏
	$scope.document = function(){
		$scope.ranking = false;
		$scope.area = false;
		$scope.price = false;
	}
	
	//用来存储搜索出的商品
	$scope.arrAll = [];
	$scope.arr = []; 
	
	//进入页面加载商品
	getShopping.initShopping(keyword,type,$scope.arr2.minPrice,$scope.arr2.maxPrice,$scope.rank,1,function(response){
		$scope.arr = response.data.goods;
	})
	
	console.log(keyword + " " + type + " " + $scope.arr2.minPrice + " " + $scope.arr2.maxPrice + " " + $scope.rank + " " + page);
    
    //数据渲染完成后的事件
    $scope.$on('ngRepeatFinished', function( ngRepeatFinishedEvent ) {
			$scope.show = false;
    })
    
    //angular的监听事件
    
    window.addEventListener("scroll", function(event) {
    	var clientHeight = $(this).height();
    	var scrollTop = $(this).scrollTop();
    	var docHeight = $(document).height();
    	//判断是否到达底部，上拉加载
        if(clientHeight + scrollTop >= docHeight){
        	num++;
        	getShopping.initShopping(keyword,type,$scope.arr2.minPrice,$scope.arr2.maxPrice,$scope.rank,num,function(response){
        		if(num = response.data.pager.pageCount){
        			$scope.hide = true;
        		}
        		if(num > response.data.pager.pageCount){
					return;
				}
				$scope.arr = $scope.arr.concat(response.data.goods);				
			})
	    }    
    });
    
})

//自定义指令,ng-repeat完成后运行
app.directive('onFinishRender',function($timeout){
	return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    }
})

//创建ng的工厂,请求商品的数据，进行依赖注入
app.factory("getShopping",function($http){
	var obj = {};
	obj.initShopping = function(searchWord,Commodity,maxP,minP,keyWord,pageN,_callback){
		var params = {
			categoryCode : Commodity,  //"商品类名"
		    	priceMin : maxP,
		    	priceMax : minP,
		    	keyword : keyWord,
		    	pageNum : pageN,
		    	pageSize:10,
		    	title : searchWord
		};
		params = $.param(params);
		$http({
	        method : "post",
	        dataType: "json",
			withCredentials: true,	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
		    crossDomain: true,
		    headers:{'Content-Type': 'application/x-www-form-urlencoded'},
		    data: params,
	        //async:true,
	        url : host + "/terminal/goods/list"
	   }).success(function(response){
	        if(response.code == 2000){
	        	_callback(response);
	        }
	    }).error(function(response){
	    	console.log(response);
	    });
	}
	return obj;
})


